import express, { Request, Response } from "express";
import dotenv from "dotenv";
import jwt, { type Secret } from "jsonwebtoken";
import User from "../models/User";

// 加载环境变量
dotenv.config();

const key: jwt.Secret = process.env.JWT_SECRET || "defaultjaydonxu";
const expiresIn: string | number = process.env.JWT_EXPIRATION || "1h"; // 确保 expiresIn 是字符串或数字

console.log("Key:", key, typeof key);
console.log("ExpiresIn:", expiresIn, typeof expiresIn);

const router = express.Router();
// 登录接口
router.post("/login", async (req: Request, res: Response) => {
  const { username, password } = req.body;
  if (!username || !password) {
    res.json({ message: "请提供用户名和密码", code: 400 });
    return;
  }
  const userInfo = await User.findOne({ where: { username } });
  if (!userInfo) {
    res.status(400).json({ message: "没有该用户" });
  } else if (userInfo.password !== password) {
    res.status(401).json({ statusMessage: "密码错误" });
  } else {
    console.log("jwt执行了>>");
    const token = jwt.sign(
      { username },
      key, // 密钥，用于签名
      { expiresIn } // 设置过期时间
    );
    const userInfoJSON = userInfo.toJSON();
    const {
      user_id,
      username: usernameTep,
      name,
      avatar,
      role_id,
    } = userInfoJSON;
    res.json({ token, user_id, username: usernameTep, name, avatar, role_id });
  }
});
// 登出接口
router.post("/logout", (req: Request, res: Response) => {
  res.status(200).json({ message: "退出成功" });
});

export default router;
